import React, {Component} from "react";
import {connect} from "dva";
import time, {currentTime, dateFormat, getMockTime} from "@/utils/time";
import echarts from "echarts";
import {addResizeHook} from "@/utils/resize";
import {PageHeaderWrapper} from "@ant-design/pro-layout";
import {Card, Col, Row, DatePicker} from "antd";
import moment from "moment";
import {trigger} from "@/utils/utils";


const {RangePicker} = DatePicker;


class ScoreTrend extends Component {

  colors = ['#5793f3', '#d14a61', '#675bba']

  state = {
    startTime: time.getStartOfDay(),
    endTime: time.getEndOfDay(),

    // 展示时间
    displayStartTime: time.getStartOfDay(),
    displayEndTime: time.getEndOfDay(),

    // 默认定时任务trigger时间
    defaultStartTime: time.getStartOfDay(),
    defaultEndTime: time.getEndOfDay(),
    currentTime: null,
    data: [],
    chart: null,
    // defaultTimeSpan: 8,
    option: {
      color: this.colors,

      tooltip: {
        trigger: 'axis',
        axisPointer: {
          type: 'cross'
        }
      },
      grid: {
        top: '3%',
        left: '5%',
        right: '1%',
        bottom: '14%'
      },
      legend: {
        data: ['蒸发量', '降水量', '平均温度']
      },
      xAxis: [
        {
          type: 'category',
          axisTick: {
            alignWithLabel: true
          },
          data: []
        }
      ],
      yAxis: [
        {
          type: 'value',
          name: '分数',
          position: 'left',
          max: 100,
          min: 0,
          splitNumber: 5,
          axisLine: {
            lineStyle: {
              color: this.colors[0]
            }
          },
          axisLabel: {
            formatter: '{value}'
          }
        }
      ],
      series: [
        {
          name: '分数',
          type: 'line',
          yAxisIndex: 0,
          data: [2.0, 2.2, 3.3, 4.5, 6.3, 10.2, 20.3, 23.4, 23.0, 16.5, 12.0, 6.2]
        }
      ]
    },
    triggerTime: new Date()
  };

  stopLoop = false;
  stopRun = false;
  reqRef = 0;

  randomId = 0;


  async componentDidMount() {
    const {hasParent = false} = this.props;

    const payload = await getMockTime("GaoLu")
    this.setState({startTime:payload.start,endTime:payload.end,
      displayStartTime:payload.start,
      displayEndTime:payload.end,
      defaultStartTime:payload.start,
      defaultEndTime:payload.end})

    // 没有父页面驱动,需要自行获取数据
    if (!hasParent) {
      this.reqRef = requestAnimationFrame(() =>
        trigger(
          this.getStatus,
          new Date().valueOf(),
          60 * 60 * 1000,
          true,
          () => this.stopLoop));
    }

    // 基于准备好的dom，初始化echarts实例
    this.state.chart = echarts.init(document.getElementById("scoreTrend"));
    // 绘制图表
    this.state.chart.setOption(this.state.option);
    addResizeHook(this, this.state.chart.resize)
  }

  componentWillUnmount() {
    cancelAnimationFrame(this.reqRef);
    this.stopLoop = true
  }

  static getDerivedStateFromProps(nextProps, prevState) {
    const {scoreTrend, globalTime,hasParent} = nextProps;
    const {option, chart} = prevState;

    if (scoreTrend && prevState.chart !== null) {
      option.series[0].data = scoreTrend.score;
      option.xAxis[0].data = scoreTrend.date.map(str => str.replace(' ', '\n'));
      chart.setOption(option, true);

      // if (globalTime&&hasParent && prevState.currentTime !== globalTime.currentTime) {
      //   debugger
      //   return {
      //     displayStartTime: new Date(globalTime.currentTime.valueOf()-24* 60* 60*1000),
      //     displayEndTime: globalTime.currentTime,
      //     startTime: new Date(globalTime.currentTime.valueOf()-24* 60* 60*1000),
      //     endTime: globalTime.currentTime,
      //     currentTime:globalTime.currentTime
      //   }
      // }
    }
    //state 不需要更改
    return null
  }

  timePick = (value) => {
    this.stopRun = false;
    this.randomId = Math.random();
    this.state.displayStartTime = value[0].toDate();
    this.state.displayEndTime = value[1].toDate();
    this.state.startTime = this.state.displayStartTime;
    this.state.endTime = this.state.displayEndTime;
    this.getStatus();

    trigger(
      () => {
        this.state.startTime = this.state.defaultStartTime;
        this.state.endTime = this.state.defaultEndTime;
        this.getStatus();
        this.setState({
          displayStartTime: new Date(this.state.startTime.valueOf()),
          displayEndTime: new Date(this.state.endTime.valueOf())
        });
        this.stopRun = true;
      },
      new Date().valueOf(),
      50 * 60 * 1000,
      false,
      () => {
        return false
      },
      (id) => {
        if (id !== this.randomId) return true;
        return this.stopRun
      },
      this.randomId);
  };

  getStatus = () => {
    const payload = {
      start: dateFormat(this.state.startTime),
      end: dateFormat(this.state.endTime)
    };
    debugger
    this.props.dispatch({
      type: 'gaolu/getScoreTrendEffect',
      payload
    });
  };


  render() {
    const {
      width = 100,
      height = 350
    }
      = this.props;
    const {displayStartTime, displayEndTime} = this.state;
    const dateFormat = 'YYYY-MM-DD HH';
    return (
      <div>
        <RangePicker
          key={Math.random()} //强制刷新组件
          style={{width: 400}}
          showTime={{format: 'HH'}}
          format={dateFormat}
          placeholder={['开始时间', '结束时间']}
          onOk={this.timePick}
          defaultValue={[moment(displayStartTime, dateFormat), moment(displayEndTime, dateFormat)]}
        />

        <div id="scoreTrend" style={{width: `${width}%`, height}}/>
      </div>

    )
  }
}

export default connect(({gaolu, global}) => ({
  scoreTrend: gaolu.scoreTrend,
  globalTime: gaolu.globalTime,
  global
}))
(ScoreTrend);
